<template>
  <div class="county-chronicle"> 
  
    <Header :activeIndex="1" :swiperPics="townInfoData.picList"></Header>

    <!-- 村志简介 -->
    <ContentInfo @toggleDropdown="toggleDropdown" :data="townInfoData">
      <template v-slot:content-bottom>
        <div class="community-down">
          <div class="community-name"></div>
          <div class="community-list">
            <div class="community-item" v-for="item in villageArr" :key="item.id" @click="handleVillageClick(item)">
              <div class="item-center">
                <div class="text">{{item.name}}</div>
              </div>
            </div>
          </div>
        </div>
      </template>
    </ContentInfo>

    <!-- 乡贤名士 -->
    <ScholarsModule :data='scholarsData'></ScholarsModule>

    <!-- 文化古迹 -->
    <CulturalHeritage :data="culturalData"></CulturalHeritage>

    <!-- 寻根问谱 -->
    <AncestralRecords :data="genealogyData"></AncestralRecords>

    <!-- 宁海文化 -->
    <NinghaiCulture :data="literatureArr"></NinghaiCulture>
    <PageFooter></PageFooter>
  </div>


  <el-dialog v-model="dialogVisible" title="" class="no-header-dialog"   width="1280" :before-close="handleClose">
    <div class="dropdown" >
      <div class="dropdown-title">乡镇街道</div>
      <ul class="dropdown-ul">
        <li class="dropdown-li" v-for="item in townArr" :key="item.id" @click="handleTownClick(item)">
          <span>{{item.name}}</span>
          <i class="arrow"></i>
        </li>

      </ul>
    </div>
  </el-dialog>
</template>
<script setup>
import Header from "@/components/Header.vue";
import ScholarsModule from "@/components/ScholarsModule.vue";
import CulturalHeritage from "@/components/CulturalHeritage.vue";
import AncestralRecords from "@/components/AncestralRecords.vue";
import NinghaiCulture from "@/components/NinghaiCulture.vue";
import ContentInfo from "@/components/ContentInfo.vue";
import ScrollingText from "@/components/ScrollingText.vue";
import PageFooter from '@/components/PageFooter.vue'

import { homeModelList, townList, chroniclesTree, townInfo, townChildList } from '@/api/common'
import { getGenealogyList } from '@/api/common_also'
import { useRoute, useRouter } from 'vue-router'
import { onMounted, onBeforeUnmount, ref, nextTick, watch } from "vue";
import { literature } from "@/hooks/literature";

const { literatureArr, getLiteratureListPage } = literature()

const route = useRoute()
const router = useRouter()

// 移除原来的 const id = route.query.id
const id = ref(route.query.id)

const dialogVisible = ref(false)
const toggleDropdown = () => { 
  console.log('toggleDropdown')
  dialogVisible.value = true
}
const handleClose = () => {
  dialogVisible.value = false
}

const setupScroll = (el) => {
  const container = el.querySelector(".item-center");
  const textEl = container?.querySelector(".text");

  if (!container || !textEl) return;

  const containerWidth = container.clientWidth;
  const textWidth = textEl.scrollWidth;

  if (textWidth <= containerWidth) return; // 不需要滚动

  const offset = textWidth - containerWidth;
  let loopTimer = null;

  const scrollOnce = () => {
    // 滚动到最后一个字
    textEl.style.transition = "transform 4s linear";
    textEl.style.transform = `translateX(-${offset}px)`;

    setTimeout(() => {
      // 平滑回到起点
      textEl.style.transition = "transform 1s ease-in-out";
      textEl.style.transform = "translateX(0px)";
    }, 4000);
  };

  const startLoop = () => {
    scrollOnce();
    loopTimer = setInterval(scrollOnce, 5100); // 总周期：4s + 1s + 少量延迟
  };

  const stopLoop = () => {
    if (loopTimer) clearInterval(loopTimer);
    loopTimer = null;
    // 强制回滚，避免卡在中间状态
    textEl.style.transition = "transform 1s ease-in-out";
    textEl.style.transform = "translateX(0px)";
  };

  // 事件绑定
  el.addEventListener("mouseenter", () => {
    if (!loopTimer) {
      startLoop();
    }
  });

  el.addEventListener("mouseleave", () => {
    stopLoop();
  });
};

// 各模块数据
const scholarsData = ref([])        // 乡贤名士
const culturalData = ref([])        // 文化古迹
const genealogyData = ref([])       // 祖先

//  乡镇信息
const townInfoData = ref({})
// 乡镇列表
const townArr = ref([])
// 村社区列表
const villageArr = ref([])

// 监听路由变化
watch(
  () => route.query.id,
  (newId) => {
    id.value = newId
    // 重新加载所有数据
    loadData()
  }
)

// 乡镇信息
const getPageInfo = () => { 
  townInfo({id:id.value}).then(res=>{ 
    let { code, data, msg } = res
    if(code === 0){
      townInfoData.value = data
    }else{
      ElMessage.warning(msg);
    }
  })
}


// 下属村list
const getVillageList = () => { 
  townChildList({
    orgId: id.value
  }).then(res => { 
    let { code, data, message } = res
    if(code === 0){
      villageArr.value = data
      nextTick(()=>{
        document.querySelectorAll(".community-item").forEach(setupScroll);
      })
    }else{
      ElMessage.warning(message);
    }
  })
}

//查询乡镇、街道列表
const getTownList = () => { 
  townChildList({
    orgId: 1
  }).then(res => { 
    let { code, data, message } = res
    if(code === 0){
      townArr.value = data
    }else{
      ElMessage.warning(message);
    }
  })
}
// 使用 Promise.all 并发请求所有数据
const getAllHomeData = () => {
  const requests = [
    homeModelList({ type: 0, orgId: id.value }), // 乡贤名士
    homeModelList({ type: 1, orgId: id.value }), // 文化古迹
  ];

  Promise.all(requests)
    .then(responses => {
      responses.forEach((res, index) => {
        let { code, data, msg } = res;
        if (code === 0) {
          switch (index) {
            case 0:
              scholarsData.value = data;
              break;
            case 1:
              culturalData.value = data;
              break;
          }
        } else {
          ElMessage.warning(msg);
        }
      });
    })
    .catch(error => {
      console.error('请求出错:', error);
      ElMessage.error('数据加载失败');
    });
}

//寻根问谱
const getGenealogyListFunction = () => { 
  getGenealogyList({
    pageNum: 1,
    pageSize: 10,
    townId: id.value
  }).then(res=>{
    let { data, msg } = res;
    // debugger
    if(res.code === '200') { 
      genealogyData.value = data.rows
    }else { 
      ElMessage.warning(msg);
    }
  })
};

// 在现有代码中添加这个方法
const handleTownClick = (item) => {
  dialogVisible.value = false
  // 跳转到村社区详情页，假设路由为 '/township'，参数为村社区ID
  router.push({ 
    path: '/township', 
    query: { id: item.id } 
  });
};

// 在现有代码中添加这个方法
const handleVillageClick = (item) => {
  dialogVisible.value = false
  // 跳转到村社区详情页，假设路由为 '/township'，参数为村社区ID
  router.push({ 
    path: '/village', 
    query: { id: item.id } 
  });
};

onMounted(() => {
  getTownList()

  loadData()
});

// 将数据加载逻辑封装成一个函数
const loadData = () => {
  getAllHomeData()
  getGenealogyListFunction()
  getPageInfo()
  getVillageList()
  getLiteratureListPage(id.value)
}


 
</script>
<style lang="scss">
.no-header-dialog{
  padding: 0;
  .el-dialog__header{
    padding-bottom: 0;
  }
 
}
</style>
<style lang="scss" scoped>
.community{
  min-width: 1280px;
}
.community-down {
  margin-top: 57px;
  padding-bottom: 30px;
  display: block;
  width: 1280px;
  display: flex;
  flex-direction: column;
  align-items: center;
  .community-name {
    width: 262px;
    height: 46px;
    background: url("@/assets/images/cz_next_title.png");
  }
  .community-list {
    display: flex;
    width: 100%;
    flex-wrap: wrap;
    margin-top: 60px;
    .community-item {
      width: 156px;
      height: 47px;
      overflow: hidden;
      white-space: nowrap;
      background: url("@/assets/images/community1.png") no-repeat;
      background-size: 100% 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 31px;
      cursor: pointer;
      margin-right: 31px;
      &:nth-child(7n){
        margin-right:0
      }
      &:hover { 
        background: url("@/assets/images/community2.png") no-repeat;
        .text{
          color: #fff;
        }
      }
      .item-center {
        position: relative;
        width: 126px; /* 固定容器宽度 */
        overflow: hidden; /* 隐藏超出内容 */
        height: 47px;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .text {
        position: absolute;
        white-space: nowrap;
        font-weight: 500;
        font-size: 18px;
        color: #aa7b3b;
        &.resetting {
          animation: resetScroll 1.5s ease-in-out forwards;
        }
      }
      .community-item:hover .text {
        animation-play-state: running; /* 悬停时播放动画 */
      }

    
    }
  }
}


.dropdown{
  padding: 35px 50px;
  background: #F5F5F5;
  width: 100%;
  z-index: 99;
  display: flex;
  &.dropdown2{
    background-color: #FFFFFF;
  }
  .dropdown-title{
    font-weight: 500;
    font-size: 22px;
    color: #111111;
    margin: 14px 0;
    width: 180px;
  }
  .dropdown-ul{
    list-style: none;
    display: flex;
    flex-wrap: wrap;
    flex: 1;

    .dropdown-li{
      display: flex;
      align-items: center;
      width: 120px;
      margin: 14px 20px;
      font-weight: 500;
      font-size: 16px;
      cursor: pointer;
      &:hover{ 
        color: #B52628;
        .arrow{
          background-image: url("@/assets/images/arrow2.png");
        }
      }

      .arrow{
        display: inline-block;
        margin-left: 12px;
        width: 14px;
        height: 14px;
        background-image: url("@/assets/images/arrow1.png");
      }
    }
  }
}
</style>
